//创建用户相关仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type'
import { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由(常量路由)
import { constantRoute } from '@/router/routes'

let useUserStore = defineStore('User', {
  //小仓库数据存储地方
  state: (): UserState => {
    return {
      // token: localStorage.getItem("TOKEN"),//用户唯一标识token
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      // //存储当前用户是否包含某一个按钮
      // buttons:[],
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      // console.log('result', result)
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data
        //本地存储持久化存储
        // localStorage.setItem("TOKEN",result.data.token)
        SET_TOKEN(result.data)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        // console.log("@@@@@",result.data.message)
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo() {
      //获取用户信息进行存储仓库当中[用户头像、名字]
      let result: userInfoReponseData = await reqUserInfo()
      // console.log('userinfo', result)
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async logout() {
      //调用退出登录接口
      let result: any = await reqLogout()
      // console.log('userinfo', result)
      if (result.code == 200) {
        //清空下面数据
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
